﻿using Sunny.UI.Win32;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NovoSerDes
{
    public class CFileExporter : InterfaceCFileExporter
    {
        private string exportCFilePath = "";
        private string exportCDirectoryPath = "";

        public CFileExporter(string _exportCFilePath)
        {
            exportCFilePath = _exportCFilePath;
            exportCDirectoryPath = System.IO.Path.GetDirectoryName(exportCFilePath);

            if (!System.IO.Directory.Exists(exportCDirectoryPath))
            {
                System.IO.Directory.CreateDirectory(exportCDirectoryPath);
            }
            if (!File.Exists(exportCFilePath))
            {
                //UIMessageDialog.ShowMessageDialog("找不到C文件,自动新建C文件", "提示", showCancelButton: false, UIStyle.Blue, showMask: false);
                // 创建一个空的 C 文件
                File.Create(exportCFilePath).Dispose(); // 创建文件并立即释放资源
                Console.WriteLine("已新建C文件");
            }
        }

        public static string CreateCFilePath()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Save C File...";
            saveFileDialog.Filter = "C Source Files (.c)|*.c";
            string defaultSaveCDirectoryPath = Path.Combine(Environment.CurrentDirectory, "C FILE");
            if (!Directory.Exists(defaultSaveCDirectoryPath))
            {
                Directory.CreateDirectory(defaultSaveCDirectoryPath);
            }
            saveFileDialog.InitialDirectory = Path.Combine(Environment.CurrentDirectory, "C FILE");
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string SaveCFilePath = saveFileDialog.FileName;
                return SaveCFilePath;
            }
            else
            {
                return null;
            }
        }

        public static byte[] SplitValue(int value, int parts)
        {
            if (parts != 2 && parts != 3)
            {
                Console.WriteLine("Error: parts must be 2 or 3.");
                return null;
            }

            byte[] result = new byte[parts];

            if (parts == 2)
            {
                byte high = (byte)((value >> 8) & 0xFF);
                byte low = (byte)(value & 0xFF);
                Console.WriteLine($"High 8 bits: 0x{high:X2}, Low 8 bits: 0x{low:X2}");
                result[0] = high;
                result[1] = low;
            }
            else if (parts == 3)
            {
                byte high = (byte)((value >> 16) & 0xFF);
                byte middle = (byte)((value >> 8) & 0xFF);
                byte low = (byte)(value & 0xFF);
                Console.WriteLine($"High 8 bits: 0x{high:X2}, Middle 8 bits: 0x{middle:X2}, Low 8 bits: 0x{low:X2}");
                result[0] = high;
                result[1] = middle;
                result[2] = low;
            }

            return result;
        }

        public void ExportCFile(List<RegisterConfig> configs)
        {
            try
            {
                /*
                自动管理资源的释放：使用using关键字自动管理对象的生命周期。在 using 块结束时，C# 会自动调用对象的 Dispose 方法。
                这对于文件操作尤其重要，因为文件句柄是有限的系统资源，未能及时释放会导致资源泄漏。
                确保 StreamWriter 在使用后被正确释放。
                */
                using (StreamWriter writer = new StreamWriter(exportCFilePath))
                {
                    writer.WriteLine("#include <stdio.h>");
                    writer.WriteLine("#define devAddr " + configs[0].DevAddr);
                    writer.WriteLine("");
                    writer.WriteLine("void configure_registers() {");

                    foreach (var config in configs)
                    {
                        writer.WriteLine($"    // {config.Comment}");
                        //writer.WriteLine($"    IICWR({config.DevAddr}, {config.RegAddr}, {config.Value});");
                        writer.WriteLine($"    IICSWr(devAddr, {config.RegAddr}, {config.Value});");
                    }

                    writer.WriteLine("}");
                }
                Console.WriteLine($"File successfully written to {exportCFilePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while writing to the file: {ex.Message}");
            }
        }
    }
}
